package com.apexedu.identity.service.impl;

import com.apexedu.biz.Const;
import com.apexedu.biz.entity.TAccessAppReg;
import com.apexedu.framework.service.impl.AbstractBaseServiceSupport;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.Pager;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.framework.util.SysPropertiesUtil;
import com.apexedu.identity.IdConstants;
import com.apexedu.identity.action.IdLoginAction;
import com.apexedu.identity.action.IdUserAction;
import com.apexedu.identity.entity.*;
import com.apexedu.identity.service.IdUserCustomExtService;
import com.apexedu.identity.service.IdUserService;
import com.apexedu.portal.constant.ActionConstant;
import com.apexedu.portal.entity.TLbxxMx;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.sys.SysConstants;
import com.apexedu.sys.entity.ApplicationEnum;
import com.apexedu.sys.util.BusinessLogUtil;
import com.apexedu.util.StringUtil;
import com.apexedu.util.crypto.LiveBosMD5;

import java.util.*;

public class IdUserServiceImpl extends AbstractBaseServiceSupport implements IdUserService {

    private IdUserCustomExtService idUserCustomExtService;

    private static List<TSysMenu> DEFAULT_MENUS;

    static final String HQL_LEFT_MENU_COLS = "select new TSysMenu(x.menuid, x.menuname, x.menupath, x.upmenuid, x.depth," +
            " x.state,x.ordernum, x.share2enterprise, x.belongtoapp, (select count(*) from TSysMenu where upmenuid=x.menuid) as childMenuCount) ";

    public TSysUser entity(String userLoginId) {
        // 登录时候查询用户信息
        String hql = "from TSysUser where userloginid = ? or username = ?";
        TSysUser user = getBaseDao().findFieldValue(hql, userLoginId, userLoginId);
        //如果user为空，从基础库查询user信息
        if(user == null){
            user = getRemoteUser(userLoginId);
        }
        return user;
    }

    public List<TSysMenu> loadMyMenu(TSysUser user) {

        List<TSysMenu> tsysMemues = null;
        if (IdConstants.USER_STATE_ALLOW_ROLEMEMU.equals(user.getState())) {
            tsysMemues = loadMenuOnlyByRole(user.getUserid());
        } else if (IdConstants.USER_STATE_ALLOW_USERMEMU.equals(user.getState())) {
            tsysMemues = loadMenuOnlyByUser(user.getUserid());
        } else if (IdConstants.USER_STATE_ALLOW_DOUBLEMEMU.equals(user.getState())) {
            tsysMemues = loadMenuByDoubleModel(user.getUserid());
        } else if(USER_STATE_BASE.equals(user.getState())){
            tsysMemues = loadDefaultMenus();
        }
        else {
            tsysMemues = new ArrayList<TSysMenu>(0);
        }
        // 去除重复元素
        if (tsysMemues != null) {
            tsysMemues = new ArrayList<TSysMenu>(new LinkedHashSet<TSysMenu>(tsysMemues));
        }
        return tsysMemues;
    }

    public List<?> list(Object myaction, Pager pager) throws Exception {
        IdUserAction action = (IdUserAction) myaction;
        TSysUser tsysUser = action.getTsysUser();
        String mydepartid = action.getLoginuser().getDepart().getDepartid();
        String hql = null;
        String qrole = action.getRequest().getParameter("qrole");// 按用户组查询
        StringBuffer sqlWhere = new StringBuffer(" where a.userloginid!='sysadmin'");
        if (StringUtil.isBlank(qrole)) {
            hql = "from TSysUser as a left join a.depart as b where b.departid like ?";
            sqlWhere.append(" and exists (select null from t_sys_depart b where b.departid=a.userdepart and b.departid like '" + mydepartid + "%')");
        } else {
            hql = "from TSysUser as a left join a.depart as b, TSysUserRole as c where a.userid=c.userid and b.departid like ?";
            hql += " and c.roleid='" + qrole + "'";
            sqlWhere.append(" and exists (select null from t_sys_depart b where b.departid=a.userdepart and b.departid like '" + mydepartid + "%')" +
                    " and exists (select null from t_sys_user_role c where c.userid=a.userid and c.roleid='" + qrole + "')");
        }
        hql += " and a.userloginid!='sysadmin'";//系统默认管理员，不能修改

        if (tsysUser != null) {
            if (tsysUser.getDepart() != null && tsysUser.getDepart().getDepartname() != null
                    && !tsysUser.getDepart().getDepartname().equals("")) {

                hql += " and b.departname like '%" + tsysUser.getDepart().getDepartname() + "%'";
                sqlWhere.append(" and exists (select null from t_sys_depart b where b.departid=a.userdepart and b.departname like '%" + tsysUser.getDepart().getDepartname() + "%')");
            }
            if (tsysUser.getUserloginid() != null && !tsysUser.getUserloginid().equals("")) {
                hql += " and a.userloginid like '%" + tsysUser.getUserloginid() + "%'";
                sqlWhere.append(" and a.userloginid like '%" + tsysUser.getUserloginid() + "%'");
            }
            if (tsysUser.getUsername() != null && !tsysUser.getUsername().equals("")) {
                hql += " and a.username like '%" + tsysUser.getUsername() + "%'";
                sqlWhere.append(" and a.username like '%" + tsysUser.getUsername() + "%'");
            }
            if (tsysUser.getState() != null && !tsysUser.getState().equals("") && !tsysUser.getState().equals("-1")) {

                if (tsysUser.getState().equals("0")) {
                    hql += " and a.state='0'";
                    sqlWhere.append(" and a.state='0'");
                } else {
                    hql += " and a.state!='0'";
                    sqlWhere.append(" and a.state!='0'");
                }
            }
        }

        String yhlx = action.getParameter("yhlx");
        if (StringUtil.isNotBlank(yhlx)) {
            hql += " and exists (select f.userid from TSysUserInfo f where f.userid=a.userid and f.yhlx='" + yhlx + "')";
            sqlWhere.append(" and exists (select null from t_sys_user_info f where f.userid=a.userid and f.yhlx='" + yhlx + "')");
            action.setParameter("yhlx", yhlx);
        } else {
            action.setParameter("yhlx", "");
        }
        String flag = action.getParameter("flag");
        String roleid = action.getParameter("roleid");
        if (StringUtil.isNotBlank(flag)) {//判断是否是显示已授权用户
            if ("authoriza".equals(flag) && StringUtil.isNotBlank(roleid)) {
                hql += " and exists (select f.userid from TSysUserRole f where f.userid=a.userid and f.roleid='" + roleid + "')";
            }
            action.setParameter("flagtype", "hide");//显示全部显示按钮
        } else {
            action.setParameter("flagtype", "show");//显示已授权按钮
        }
        pager.setTotalRows(getBaseDao().count("select count(*) " + hql, mydepartid + "%"));
        hql = "select new TSysUser(a.userid, a.userloginid, a.username, a.state, b.departname, " +
                "a.usertype, a.lastlogintime, a.logintimes, a.lastloginip) " + hql
                + " order by a.userid desc";
        List<TSysUser> tsysUsers = getBaseDao().findPageByHql(hql, pager, mydepartid + "%");
        action.setParameter("allRoles", getAllRoles());

        String type = action.getParameter("type");//type为role时为批量授权用户角色
        action.setParameter("type", type);
        action.getSession().setAttribute("userRoleSql", sqlWhere.toString());
        return tsysUsers;
    }

    public void load(Object myaction) throws Exception {
        // 打开一个用户的信息
        IdUserAction action = (IdUserAction) myaction;
        String userid = action.getParameter("wid");
        String hql = "from TSysUser where userid = ?";
        TSysUser user = (TSysUser) getBaseDao().findFieldValue(hql, userid);
        action.setTsysUser(user);
        action.setParameter("menues", queryUserMenuid(userid));
        action.setParameter("allRoles", getAllRoles());
        action.setParameter("roles", queryUserRolesId(userid));
        action.setParameter("rolesId", getRoleId(userid));
        List<TAccessAppReg> getAccessApps = getAccessApp();
        action.setParameter("appid", getAccessApps.size() > 0 ? getAccessApps.get(0).getAppid() : "");
        /****查询所有的接入系统*****/
        action.setParameter("AccessApp", getAccessApps);

    }

    @Override
    public void openCreate(Object myaction) throws Exception {

        IdUserAction action = (IdUserAction) myaction;
        action.setParameter("allRoles", getAllRoles());
        /****查询所有的接入系统*****/
        action.setParameter("AccessApp", getAccessApp());
    }

    /**
     * 事务控制交给spring
     */
    public boolean remove(Object myaction) throws Exception {
        IdUserAction action = (IdUserAction) myaction;
        String ids = action.getParameter("wid");
        if (StringUtil.isBlank(ids)) {
            throw new Exception("缺少参数！");
        }
        String userid = action.getLoginuser().getUserid();
        if (ids.equals(userid)) {
            throw new Exception("不能删除自己！");
        }
        removeMenu(ids);

        removeRole(ids);

        List<TSysUser> sysUsers = null;
        if (idUserCustomExtService != null) {
            // spring容器配置了用户自定义扩展类
            String hql = "from TSysUser where " + DBUtil.spellSqlWhere("userid", "=", ids.split(","));
            sysUsers = getBaseDao().findByHql(hql);
        }
        boolean deleteSuccess = getBaseDao().deleteAll("TSysUser", "userid", "=", ids);
        if (deleteSuccess) {
            BusinessLogUtil.log(action.getLoginuser().getUserloginid(), SysConstants.CZDX_T_SYS_USER,
                    Const.LOG_ACTION_DEL, action.getRequest().getRemoteAddr());
            if (idUserCustomExtService != null) {
                // 本系统删除成功，通知客户端方法
                idUserCustomExtService.afterRemove(sysUsers);
            }
        }
        return deleteSuccess;
    }

    private boolean removeMenu(String ids) throws Exception {
        return getBaseDao().deleteAll("TSysUserMenu", "userid", "=", ids);
    }

    private boolean removeRole(String ids) throws Exception {
        return getBaseDao().deleteAll("TSysUserRole", "userid", "=", ids);
    }

    public void saveOrUpdate(Object myaction) throws Exception {
        IdUserAction action = (IdUserAction) myaction;
        TSysUser tsysUser = action.getTsysUser();
        // 下面把菜单保存到页面显示
        action.setParameter("menues", action.getParameter("menues"));
        action.setParameter("allRoles", getAllRoles());
        action.setParameter("roles", action.getParameters("roles"));
        if (tsysUser.getUserid() == null || tsysUser.getUserid().equals("")) {
            String hql = "select count(*) from TSysUser where userloginid=? ";
            long i = getBaseDao().count(hql, tsysUser.getUserloginid());
            if (i > 0) {
                // 登录账户不允许重复
                throw new RuntimeException("登录账号已经存在，请更换其他账号！");
            }
            tsysUser.setUserid(SeqFactory.getNewSequenceAlone());
            if (tsysUser.getUserpwd() == null) {
                // 如果用户没有指定密码，则使用初始化密码
                String defaultPwd = SysPropertiesUtil.get(IdConstants.DEFAULT_PASSWORD);
                if (StringUtil.isNotBlank(defaultPwd)) {
                    tsysUser.setUserpwd(defaultPwd);//是否需要MD5密码
                } else {
                    throw new RuntimeException("密码不能为空！");
                }
            }

            if (SysPropertiesUtil.getBoolean(IdConstants.SWITCH_PASSWORD_MD5)) {
                tsysUser.setUserpwd(LiveBosMD5.getMD5Digest(tsysUser.getUserpwd()).toUpperCase());//是否需要MD5密码
            }
            getBaseDao().save(tsysUser);

            saveUserRoles(action);

            // 新增用户菜单
            saveUserMenues(action);
            String clientIP = IdLoginAction.getIpAddr(action.getRequest());
            BusinessLogUtil.log(action.getLoginuser().getUserloginid(), SysConstants.CZDX_T_SYS_USER,
                    Const.LOG_ACTION_SAVE, clientIP);
            //判断用户状态是否为禁用，如果禁用不调用同步；
            if (idUserCustomExtService != null && !tsysUser.getState().equals("0")) {
                // spring容器配置了用户自定义扩展类
                idUserCustomExtService.afterAdd(tsysUser);
            }
            // action.setParameter("rolesId", getRoleId(tsysUser.getUserid()));
        } else {

            String hql = "select userloginid from TSysUser where userid=?";
            String userLoginId = (String) getBaseDao().findFieldValue(hql, tsysUser.getUserid());
            if (!userLoginId.equals(tsysUser.getUserloginid())) {
                // 登录账户不允许重复
                throw new Exception("登录账号不可更改，请恢复先前的账号再提交！");
            }
            removeUserRoles(action);

            saveUserRoles(action);

            // 更新用户菜单
            updateUserMenues(action);

            String userPwd_hide = action.getRequest().getParameter("userPwd_hide");
            if (StringUtil.isNotBlank(userPwd_hide) && !userPwd_hide.equals(tsysUser.getUserpwd())) {
                //密码被修改了，要更新
                if (SysPropertiesUtil.getBoolean(IdConstants.SWITCH_PASSWORD_MD5)) {
                    tsysUser.setUserpwd(LiveBosMD5.getMD5Digest(tsysUser.getUserpwd()).toUpperCase());//是否需要MD5密码
                }
            }

            getBaseDao().update(tsysUser);
            BusinessLogUtil.log(action.getLoginuser().getUserloginid(), SysConstants.CZDX_T_SYS_USER,
                    Const.LOG_ACTION_UPDATE, action.getRequest().getRemoteAddr());
            //判断用户状态是否为禁用，如果禁用不调用同步；
            if (idUserCustomExtService != null && !tsysUser.getState().equals("0")) {
                // spring容器配置了用户自定义扩展类
                idUserCustomExtService.afterUpdate(tsysUser);
            }

        }
        /****查询所有的接入系统*****/
        action.setParameter("AccessApp", getAccessApp());
        action.setParameter("rolesId", action.getParameter("rolesId"));
    }

    /**
     * 取得此用户的权限菜单
     *
     * @param userid
     * @return
     */
    protected String queryUserMenuid(String userid) {

        String hql = "select menuid from TSysUserMenu where userid=?";
        List<TSysUserMenu> menues__ = getBaseDao().findByHql(hql, userid);
        StringBuffer menues = new StringBuffer("");
        for (Object menu : menues__) {
            if (menu != null) {
                menues.append(menu).append(",");
            }
        }
        if (menues.length() > 0) {
            menues.delete(menues.length() - 1, menues.length());
        }
        return menues.toString();
    }

    /**
     * 取得此用户的所属角色
     *
     * @param userid
     * @return
     */
    protected String[] queryUserRolesId(String userid) {

        String hql = "select a.roleid from TSysRole a, TSysUserRole b where a.roleid=b.roleid and a.state=1 and b.userid=?";
        List<String> roles = getBaseDao().findByHql(hql, userid);
        String[] ss = new String[roles.size()];
        return roles.toArray(ss);
    }

    /**
     * 取得此用户的所属角色
     *
     * @return
     */
    public List<TSysRole> getAllRoles() {

        String hql = "from TSysRole where state = '1' order by roleid";
        List<TSysRole> roles = getBaseDao().findByHql(hql);
        return roles;
    }

    /**
     * 将门户User表中的数据同步到t_sys_user
     *
     * @return
     */
    @Override
    public String exportUsers() {
        String msg = "";
        long success = 0;
        long error = 0;
        /************************第一步，查看用户在t_sys_user中所有存在的用户，并将存在的用户执行更新操作****************************/
        String hql_noExists = "update t_sys_user t set(t.username)=(select u.firstname from user_ u where u.screenname=t.userloginid) " +
                "where exists(select s.screenname from user_ s where s.screenname=t.userloginid)";
        int update = DBUtil.executeSQL(hql_noExists);
        /************************第二步，查询所有t_sys_user中不存在的数据，并将数据插入到用户表中**********************/
        String hql_insert = "select * from user_ t where not exists(select s.userloginid from t_sys_user s where s.userloginid=t.screenname )";
        List<User> list = DBUtil.queryAllBeanList(hql_insert, User.class);
        if (null != list && list.size() > 0) {
            List<TSysUser> userList = new LinkedList<TSysUser>();
            TSysDepart depart = getBaseDao().findById(TSysDepart.class, "000");
            for (User user : list) {
                TSysUser tSysUser = new TSysUser();
                if (StringUtil.isNotBlank(user.getScreenname())) {
                    String id = SeqFactory.getNewSequenceAlone();
                    tSysUser.setUserid(id);//wid
                    tSysUser.setUserloginid(user.getScreenname());//登录帐号
                    tSysUser.setUsername(user.getFirstname());//登录姓名
                    tSysUser.setUserpwd(user.getPassword());//密码
                    tSysUser.setState("1");//默认为1，启用状态
                    tSysUser.setUsertype("2");//默认为2，普通用户
                    tSysUser.setDepart(depart);//用户组
                    userList.add(tSysUser);
                    success++;
                } else {
                    error++;
                }
            }
            getBaseDao().saveAll(userList);
        }
        msg = "成功添加用户：" + success + " 条 <br/>" + "成功更新用户：" + update + " 条 <br/>" + " 添 加 失 败：" + error + " 条";
        return msg;
    }

    /**
     * 插入用户和用户组关联关系
     *
     * @param action
     */
    protected void saveUserRoles(IdUserAction action) {

        TSysUser tsysUser = action.getTsysUser();
        //Object[] roles = action.getParameters("rolesId");
        String roles = action.getParameter("rolesId");
        if (StringUtil.isNotBlank(roles)) {
            String[] role = roles.split(",");
            if (null != role && role.length > 0) {
                List<TSysUserRole> list = new ArrayList<TSysUserRole>();
                for (String roleId : role) {
                    if (StringUtil.isNotBlank(roleId)) {
                        TSysUserRole userRole = new TSysUserRole();
                        userRole.setId(SeqFactory.getNewSequenceAlone());
                        userRole.setUserid(tsysUser.getUserid());
                        userRole.setRoleid(roleId);
                        list.add(userRole);
                    }
                }
                if (!list.isEmpty())
                    getBaseDao().saveAll(list);
            }
        }
    }

    /**
     * 删除用户和用户组关联关系
     *
     * @param action
     */
    protected void removeUserRoles(IdUserAction action) {

        TSysUser tsysUser = action.getTsysUser();
        getBaseDao().deleteAll("TSysUserRole", "userid", "=", tsysUser.getUserid());
    }

    /**
     * 更新权限，添加用户菜单关联
     *
     * @param action
     */
    protected void saveUserMenues(IdUserAction action) {

        String menues = action.getParameter("menues");
        if (menues != null && !menues.equals("") && !menues.equals("000")) {
            // 更新权限，用户菜单关联表
            TSysUser tsysUser = action.getTsysUser();
            menues = menues.replaceAll("000,", "");// 000节点是树的根节点，在权限菜单表中不需要保存

            String[] menues__ = menues.split(",");
            List<TSysUserMenu> userMenues = new ArrayList<TSysUserMenu>(menues__.length);
            for (int i = 0; i < menues__.length; i++) {
                String o = menues__[i];
                TSysUserMenu usermenu = new TSysUserMenu();
                usermenu.setId(SeqFactory.getNewSequenceAlone());
                usermenu.setUserid(tsysUser.getUserid());
                usermenu.setMenuid(o.trim());
                userMenues.add(usermenu);
                /*
                 * if(i%10==0 || i==menues__.length-1){ //满10，或者到最后一个了，做批量保存
				 * getBaseDao
				 * ().getHibernateTemplate().saveOrUpdateAll(userMenues);
				 * userMenues.clear(); }
				 */
            }
            getBaseDao().saveAll(userMenues);
            // do_menues.delete( do_menues.length()-1, do_menues.length() );

			/*
             * String menues_return =
			 * DBUtil.execOracleProcQueryString(Config.getProcName
			 * ("proc_id_add_usermenues"), tsysUser.getUserid(),
			 * do_menues.toString()); if(menues_return==null ||
			 * !menues_return.equals( Constants.MESSAGE_RETURN_SUCCESS_CODE )){
			 * throw new Exception("用户修改失败。原因：设置权限菜单失败！"); }
			 */
        }
    }

    /**
     * 更新权限，更新用户菜单关联
     *
     * @param action
     */
    protected void updateUserMenues(IdUserAction action) {

        String menues = action.getParameter("menues");
        if (menues == null) {
            return;
        } else if (menues.equals("")) {

            TSysUser tsysUser = action.getTsysUser();
            getBaseDao().deleteAll("TSysUserMenu", "userid", "=", tsysUser.getUserid());
        } else if (!menues.equals("000")) {
            // 用户修改部分菜单的情况。考虑到效率，采用只删除用户去掉的菜单，新增用户新选的菜单
            TSysUser tsysUser = action.getTsysUser();
            // 更新权限菜单表。把数据库中的和用户新提交的菜单比较，采用删除没有的，只添加新增的菜单的策略，提高效率
            menues = menues.replaceAll("000,", "");// 000节点是树的根节点，在权限菜单表中不需要保存

            String hql = "select menuid from TSysUserMenu where userid=?";
            List<String> db_menues = getBaseDao().findByHql(hql, tsysUser.getUserid());
            if (db_menues == null) {
                db_menues = Collections.emptyList();
            } else if (!db_menues.isEmpty()) {
                db_menues.remove("000");
            }
            List<String> db_menues__clone = new ArrayList<String>(db_menues);

            Object[] curr_menu = menues.split(",");
            List<String> curr_menues = new ArrayList<String>(curr_menu.length);
            for (Object o : curr_menu) {
                curr_menues.add(o.toString());
            }

            db_menues.removeAll(curr_menues);
            // 剩下的是需要删除的菜单
            if (db_menues.isEmpty() == false) {

                StringBuffer do_menues = new StringBuffer(" and (");
                hql = "delete from TSysUserMenu where userid=?";
                for (Object o : db_menues) {
                    if (null != o) {
                        do_menues.append(" menuid='").append(o.toString()).append("' or ");
                    }
                }
                int _s = do_menues.lastIndexOf(" or ");
                if (_s > 0) {
                    do_menues.delete(_s, do_menues.length());
                    do_menues.append(")");
                    hql = hql + do_menues;
                }
                getBaseDao().delete(hql, tsysUser.getUserid());
            }

            curr_menues.removeAll(db_menues__clone);
            // 剩下的是需要增加的菜单
            if (curr_menues.isEmpty() == false) {

                // StringBuffer do_menues = new StringBuffer("");
                List<TSysUserMenu> userMenues = new ArrayList<TSysUserMenu>(curr_menues.size());
                for (int i = 0; i < curr_menues.size(); i++) {
                    Object o = curr_menues.get(i);
                    // do_menues.append(o.toString()).append(",");
                    TSysUserMenu usermenu = new TSysUserMenu();
                    usermenu.setId(SeqFactory.getNewSequenceAlone());
                    usermenu.setUserid(tsysUser.getUserid());
                    usermenu.setMenuid(o.toString().trim());
                    userMenues.add(usermenu);
                }
                getBaseDao().saveAll(userMenues);
            }
        }

    }

    /*
     * (non-Javadoc)
     * @see
     * com.imchooser.framework.identity.service.IdUserService#modifyPassword
     * (com.imchooser.framework.identity.entity.TSysUser,
     * com.imchooser.framework.identity.entity.TSysUser)
     */
    public String modifyPassword(TSysUser sessionUser, TSysUser user) {

        String mess = null;
        if (sessionUser == null || user == null) {
            mess = "用户信息不存在！";
        } else {
            if (StringUtil.isBlank(user.getUserpwd())) {
                return "请输入新密码！";
            }
            String userId = sessionUser.getUserid();
            if (StringUtil.isBlank(userId)) {
                return "userId丢失！";
            }
            if (SysPropertiesUtil.getBoolean(IdConstants.SWITCH_PASSWORD_MD5)) {
                user.setUsername(LiveBosMD5.getMD5Digest(user.getUsername()).toUpperCase());//需要MD5密码。UserName存储用户提交的原密码
                user.setUserpwd(LiveBosMD5.getMD5Digest(user.getUserpwd()).toUpperCase());//需要MD5密码
            }
            if (sessionUser.getUserpwd().equals(user.getUsername())) {
                // getUserName存储用户提交的原密码
                String hql = "update TSysUser set userpwd=? where userid=?";
                try {
                    getBaseDao().executeHql(hql, user.getUserpwd(), userId);
                    mess = "修改成功";
                    sessionUser.setUserpwd(user.getUserpwd());// 更新session中的为新密码
                } catch (Exception e) {
                    mess = "修改失败：" + e.getMessage();
                }
            } else {
                mess = "您输入的原密码错误！";
            }
        }
        return mess;
    }

    /**
     * 加载用户拥有的菜单（指所属用户组拥有的菜单）
     *
     * @param userid 登录用户的编号
     * @return
     */
    private List<TSysMenu> loadMenuOnlyByRole(String userid) {
        //从基础库获取用户信息（userId， roleId);
        String hql = HQL_LEFT_MENU_COLS + "from TSysMenu x, TSysRoleMenu a, TSysRole b, TSysUserRole c "
                + "where a.roleid=b.roleid and b.roleid=c.roleid and c.userid=? and x.menuid=a.menuid "
                + "and x.state=1 and b.state=1 and x.state=1 order by x.upmenuid,x.ordernum desc ";
        List<TSysMenu> tsysMemues = getBaseDao().findByHql(hql, userid);
        return tsysMemues;
    }

    /**
     * 加载用户拥有的菜单（指为某个用户单独指定的菜单）
     *
     * @param userid 登录用户的编号
     * @return
     */
    private List<TSysMenu> loadMenuOnlyByUser(String userid) {

        String hql = HQL_LEFT_MENU_COLS + "from TSysMenu x, TSysUserMenu m where x.state=1 and m.userid=? and x.menuid=m.menuid" +
                " order by x.upmenuid,x.ordernum desc";
        List<TSysMenu> tsysMemues = getBaseDao().findByHql(hql, userid);
        return tsysMemues;
    }

    /**
     * 加载用户拥有的菜单（包含为某个用户单独指定的菜单 和 通过用户组继承的菜单）
     *
     * @param userid 登录用户的编号
     * @return
     */
    private List<TSysMenu> loadMenuByDoubleModel(String userid) {
        // HQL 不支持 union 语句
        String hql = HQL_LEFT_MENU_COLS + "from TSysMenu x where x.state=1 and (exists ( "
                + " select '1' as menuid from TSysRoleMenu a, TSysRole b, TSysUserRole c "
                + " where a.roleid=b.roleid and b.roleid=c.roleid and b.state=1 and c.userid=? and x.menuid=a.menuid) "
                + " or exists ( select '1' as menuid from TSysUserMenu m where m.userid=? and m.menuid=x.menuid) ) " +
                " and x.belongtoapp=?"
                + " order by x.upmenuid, x.ordernum desc";

        List<TSysMenu> tsysMemues = getBaseDao().findByHql(hql, userid, userid, Const.AuCenterAccessEnterCode);
        return tsysMemues;
    }

    @Override
    public List<TSysButton> loadMyMenuButton(TSysUser user) {
        String hql = " select new TSysButton(b.buttonid, b.buttonname, b.buttonevent,"
                + " b.buttonicon, b.state,b.share2enterprise, b.memo, b.ordernum, a.menuid)"
                + " from TSysRoleMenuButton a, TSysButton b, TSysUserRole c, TSysUser d "
                + " where a.roleid=c.roleid and a.buttonid=b.buttonid and c.userid=d.userid"
                + " and d.userloginid=? and b.state=1 order by b.ordernum desc";
        return getBaseDao().findByHqlWithSecondCache(true, hql, user.getUserloginid());
    }

    public IdUserCustomExtService getIdUserCustomExtService() {
        return idUserCustomExtService;
    }

    public void setIdUserCustomExtService(IdUserCustomExtService idUserCustomExtService) {
        this.idUserCustomExtService = idUserCustomExtService;
    }

    /**
     * 获取 所属部门的下拉框数据,返回拼装后的js数据
     */
    public String departsJS() {
        StringBuilder js = new StringBuilder();
        js.append("var countries = {};").append("countries.results = [");

        //String sql = "select areaid as id,areaname as name from T_SYS_AREA";
        String sql = "select departid as id, departname as caption from T_SYS_DEPART";
        Pager pager = new Pager();
        pager.setEachPageRows(20);
        List<ApplicationEnum> list = DBUtil.queryPageBeanList(pager, sql, ApplicationEnum.class);
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                ApplicationEnum applicationEnum = list.get(i);
                js.append("{id:'").append(applicationEnum.getId()).append("',name:'").append(applicationEnum.getCaption()).append("'}");
                if (i < list.size() - 1) {
                    js.append(",");
                }
            }
        }
        js.append("];").append("countries.total = countries.results.length;");
        return js.toString();
    }

    /**
     * 查询所有的接入系统
     *
     * @return
     */
    public List<TAccessAppReg> getAccessApp() {
        String hql = "from TAccessAppReg t where t.state='1' order by ordernum desc,appid ";
        List<TAccessAppReg> list = getBaseDao().findByHql(hql);
        return list;
    }

    /**
     * 查询用户角色
     *
     * @param userId
     * @return
     */
    public String getRoleId(String userId) {
        StringBuilder roles = new StringBuilder("");
        if (StringUtil.isNotBlank(userId)) {
            List<TSysUserRole> list = DBUtil.queryAllBeanList("select  t.roleid from t_sys_user_role t where t.userid = ? ", TSysUserRole.class, userId);
            if (null != list && list.size() > 0) {
                for (TSysUserRole tSysUserRole : list) {
                    roles.append("," + tSysUserRole.getRoleid());
                }
            }
        }
        if (StringUtil.isNotBlank(roles.toString())) {
            return roles.toString().substring(1, roles.toString().length());
        }
        return roles.toString();
    }
    //从基础库查询user信息
    @Override
    public TSysUser getRemoteUser(String userLoginId){
        TSysUser user = null;
        DBMUtil dbm = new DBMUtil(ActionConstant.SzGz.DATA_SOURCE_BASE);
        String sql = " select * from TUSER WHERE USERID=?";
        try {
            TUser result = dbm.queryBean(sql, TUser.class, userLoginId);
            if(result != null){
                user = new TSysUser();
                user.setUserloginid(result.getUserid());
                user.setUsername(result.getName());
                user.setUserpwd(result.getPassword());
                user.setState(USER_STATE_BASE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
    //查询默认菜单
    public synchronized List<TSysMenu> loadDefaultMenus(){
        if(DEFAULT_MENUS == null){
            String hql = HQL_LEFT_MENU_COLS + "from TSysMenu x where x.state=1 and x.des = ?"
                    + " order by x.upmenuid, x.ordernum desc";

            List<TSysMenu> tsysMemues = getBaseDao().findByHql(hql, MENU_DEFAULT_FLAG);
            DEFAULT_MENUS = tsysMemues;
        }
        return DEFAULT_MENUS;
    }

}
